package cn.com.xinjinfu.pdoulcProduct.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import org.json.JSONObject;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.WebView.BindWeiXinWeb;
import cn.com.xinjinfu.pdoulcProduct.activity.AboutPdouAct;
import cn.com.xinjinfu.pdoulcProduct.activity.DoWorkActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.InviteFriendsAct;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseWebActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.login.CheckMobileActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.FindBean;
import cn.com.xinjinfu.pdoulcProduct.entity.FindBean.OfficialNews;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.utils.SharedPreferencesUtils;
import cn.com.xinjinfu.pdoulcProduct.view.ListViewForScrollView;

/**
 * Created by android-adt on 2015/12/29.
 */
public class FindFragment extends BaseFragment implements View.OnClickListener {
    private static String NEWSID = "-1";
    private RequestQueue requen;
    private static final String TAG = "FindFragment";
    private Activity mActivity;
    private ImageView img_do_work;
    private RelativeLayout rl_do_work, rl_invite_friends, rl_about_pdou,rl_safl,rl_problem, rl_bing_weixin;
    private FindBean findBean;
    public static boolean isHidden;
    private ListViewForScrollView mListView;
    private MyAdapter myAdapter;
    private List<OfficialNews> myofficialList;
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = activity;
    }

    public void loginLoad() {
//        if (SharedPreferencesUtils.getOfficialId(mActivity, "officialListMaxId") != "") {
//            NEWSID = SharedPreferencesUtils.getOfficialId(mActivity, "officialListMaxId");
//        }
        requen = Volley.newRequestQueue(mActivity);
        loginRequest();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find, container, false);
        initViews(view);
        return view;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loginLoad();
    }


    /**
     * 控件初始化
     */
    private void initViews(View view) {
        TextView tv_title = (TextView) view.findViewById(R.id.top_title_tv);
        tv_title.setText("发现");

        rl_do_work = (RelativeLayout) view.findViewById(R.id.rl_do_work);
        rl_invite_friends = (RelativeLayout) view.findViewById(R.id.rl_invite_friends);
        rl_bing_weixin = (RelativeLayout) view.findViewById(R.id.rl_bing_weixin);
        rl_about_pdou = (RelativeLayout) view.findViewById(R.id.rl_about_pdou);
        rl_safl = (RelativeLayout) view.findViewById(R.id.rl_safl);
        rl_problem = (RelativeLayout) view.findViewById(R.id.rl_problem);
        rl_do_work.setOnClickListener(this);
        rl_invite_friends.setOnClickListener(this);
        rl_bing_weixin.setOnClickListener(this);
        rl_about_pdou.setOnClickListener(this);
        rl_safl.setOnClickListener(this);
        rl_problem.setOnClickListener(this);

        img_do_work = (ImageView) view.findViewById(R.id.img_do_work);


        mListView = (ListViewForScrollView) view.findViewById(R.id.mListView);
        myAdapter = new MyAdapter(mActivity);
        mListView.setAdapter(myAdapter);

        /**************禁止ScrollView自动滑动到底部*********************/
        View ll_tou = view.findViewById(R.id.ll_tou);
        ll_tou.setFocusable(true);
        ll_tou.setFocusableInTouchMode(true);
        ll_tou.requestFocus();

    }

    private void initBanner() {
        if (findBean.getNewsNumber() > 0 ){
            isHidden = true;
        }else {
            isHidden = false;
        }
        if (findBean.isFinishNormalTask()) {
            img_do_work.setImageResource(R.drawable.icon_fx_rw2);
        } else {
            img_do_work.setImageResource(R.drawable.icon_fx_rw);
        }
        myofficialList = findBean.getOfficialNews();
        if (!(myofficialList==null||myofficialList.equals("null")||myofficialList.size()<1)){
            myAdapter.setMyList(myofficialList);
//            NEWSID = myofficialList.get(0).getId() + "";
//            SharedPreferencesUtils.saveOfficialId(mActivity, "officialListMaxId",NEWSID);
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.rl_do_work:
                User user = AccountManager.getInstance().getUser();
                if (user != null && user.getCurrUser().isLogged()) {
                    startActivity(new Intent(mActivity, DoWorkActivity.class));
                } else {
                    startActivity(new Intent(mActivity, CheckMobileActivity.class));
                }
                break;
            case R.id.rl_invite_friends:
                startActivity(new Intent(mActivity, InviteFriendsAct.class));
                break;
            case R.id.rl_bing_weixin:
                String url = DataHandler.WEBURL+"/front/wa/attentionWP";//绑定微信
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                Intent intent0 = new Intent(mActivity, BindWeiXinWeb.class);
                intent0.putExtras(bundle);
                mActivity.startActivity(intent0);
                break;
            case R.id.rl_about_pdou:
                intent.setClass(mActivity, AboutPdouAct.class);
                intent.putExtra("CurrentItem", "aboutpdou");//也可以绑定数组
                startActivity(intent);

                break;
            case R.id.rl_safl:
                intent.setClass(mActivity, AboutPdouAct.class);
                intent.putExtra("CurrentItem", "safl");//也可以绑定数组
                startActivity(intent);
                break;
            case R.id.rl_problem:
                intent.setClass(mActivity, AboutPdouAct.class);
                intent.putExtra("CurrentItem", "problem");//也可以绑定数组
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    /**
     * 网络请求
     */
    private void loginRequest() {
        final Map<String, String> parameters = DataHandler.getParameters("1421");
        User user = AccountManager.getInstance().getUser();
        if (user != null && user.getCurrUser().isLogged()) {
            parameters.put("id", user.getCurrUser().getSign());
        }
        parameters.put("newsId", "-1");
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
        requen.add(request);
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            DataHandler.errorHandler(mActivity, error);
            if (SharedPreferencesUtils.getUserInfo(mActivity, "findBean") != ""){
                findBean=JSON.parseObject(SharedPreferencesUtils.getUserInfo(mActivity, "findBean"), FindBean.class);
                initBanner();
                myAdapter.notifyDataSetChanged();
            }
        }
    };

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            if (JSONManager.getError(jobj) == -1) {
                SharedPreferencesUtils.saveUserInfo(mActivity, "findBean", jobj.toString());
                findBean = JSON.parseObject(jobj.toString(), FindBean.class);
                initBanner();
                myAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    public String getFragmentName() {
        return TAG;
    }

    @Override
    protected void lazyLoad() {
    }

    public class MyAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;
        private List<OfficialNews> myList;
        private ImageLoader imageLoader;
        private DisplayImageOptions options;


        public MyAdapter(Context context){
            inflater = LayoutInflater.from(context);
            this.context = context;
            imageLoader = ImageLoader.getInstance();
            options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.banner_bg) // 设置图片下载期间显示的图片
                    .showImageForEmptyUri(R.drawable.banner_bg) // 设置图片Uri为空或是错误的时候显示的图片
                    .showImageOnFail(R.drawable.banner_bg) // 设置图片加载或解码过程中发生错误显示的图片
                    .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                    .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                    .considerExifParams(true)
                    .resetViewBeforeLoading(false)  // default 设置图片在加载前是否重置、复位
                    .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .displayer(new FadeInBitmapDisplayer(30))
                    .build();
        }

        public void setMyList(List<OfficialNews> imageIdList){
            this.myList = imageIdList;
        }

        @Override
        public int getCount() {
            return myList == null ? 0 :myList.size();
        }

        @Override
        public Object getItem(int position) {
            return myList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View view, ViewGroup parent) {
            final ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = inflater.inflate(R.layout.item_official_info, null);
                holder.imageView = (ImageView) view.findViewById(R.id.img_cc);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            String url = this.myList.get(position).getImage_filename();
            if (!(url.indexOf("http")>=0)){
                url = DataHandler.DOMAIN + url;
            }
            holder.imageView.setTag(url);
            String tag = (String)holder.imageView.getTag();

            //获得组件当前的tag，与传入的内容比较，一至的才能显示
            if(tag!=null && tag.equals(url)) {
                imageLoader.displayImage(url, holder.imageView, options, new SimpleImageLoadingListener(){

                    final List<String> displayedImages = Collections
                            .synchronizedList(new LinkedList<String>());
                    public void onLoadingComplete(String imageUri, View view,
                            Bitmap loadedImage) {
                        if (loadedImage != null) {
                            ImageView imageView = (ImageView) view;
                            boolean firstDisplay = !displayedImages.contains(imageUri);
                            if (firstDisplay) {
                                FadeInBitmapDisplayer.animate(imageView, 500); // 设置image隐藏动画500ms
                                displayedImages.add(imageUri); // 将图片uri添加到集合中
                            }
                        }
                    }
                }
                );
            }
            holder.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    String url = DataHandler.WEBURL + "/front/wa/officialNewsDetail?newsId=" + myList.get(position).getId();
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putString("title", myList.get(position).getTitle());
                    Intent intent = new Intent(context, BaseWebActivity.class);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            });

            return view;
        }
        public class ViewHolder {
            ImageView imageView;
        }
    }


}